package cn.com.xyc.common.security;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import cn.com.xyc.pojo.Admin;
import cn.com.xyc.service.SystemService;

public class ShiroDataBaseRealm extends AuthorizingRealm{
	@Autowired
	private SystemService systemService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		Admin admin=(Admin)arg0.fromRealm(getName()).iterator().next();
		SimpleAuthorizationInfo auInfo=new SimpleAuthorizationInfo();
		auInfo.addRole("admin");
		return auInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		Admin user = systemService.findByUsername(username);
		if (user == null) {
			throw new UnknownAccountException();
		}
		if ("0".equals(user.getStatus())) {
			throw new LockedAccountException();
		}
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				user, user.getPassword(),ByteSource.Util.bytes(user.getCredentialsSalt()), getName());
		return authenticationInfo;
	}

}
